#include "Qt3DPicker.h"

#include "ReverseHandler.h"
#include "CmdManager.h"
#include "Scene.h"
#include "SendPointHandlerBase.h"
#include "SelectHandler3D.h"
#include "OSGNodeMask.h"
#include "Operation/OpReverse.h"
#include "Polygon.h"

ReverseHandler::ReverseHandler()
{
}

ReverseHandler::~ReverseHandler()
{
}

void ReverseHandler::input(const QVariant& data, const QString& rawInput, CommandSource cs)
{
	auto sph = getSendPointHandler();
	auto scene = getScene();
	auto selector = qobject_cast<SelectHandler3D*>(getSelectHandler());
	if (data.type() == QVariant::Bool && !data.toBool())
	{
		if (selector)
			selector->clearSelection();
		emit finished();
		return;
	}

	if (status() == 0)
	{
		if (selector)
		{
			auto pickHandler3D = getPicker();
			selector->clearSelection();
			selector->beginSelect(D3SurfaceMask);
			prompt(1, tr("选择要反转的面或[所有多边形(P)]: "));
		}
		return;
	}

	if (status() == 1)
	{
		if (selector && selector->done())
		{
			auto selections = selector->selectionSet();
			if (selections.size() > 0)
			{
				auto undoStack = scene->undoStack();
				std::set<std::shared_ptr<Ent3DFace>> faces;			
				for (auto selection : selections)
				{
					auto face = std::dynamic_pointer_cast<Ent3DFace>(selection);
					faces.insert(face);
				}	
				selector->clearSelection();
				undoStack->push(new OpReverse(faces));
				emit finished();
				return;
			}
		}
		else if (rawInput.compare("p", Qt::CaseInsensitive) == 0)
		{
			auto children = scene->getChildren();
			std::set<std::shared_ptr<Ent3DFace>> faces;
			for (auto child : children)
			{
				auto polygon = std::dynamic_pointer_cast<Polygon>(child);
				if (polygon)
				{
					faces.insert(polygon);
				}
			}
			auto undoStack = scene->undoStack();
			undoStack->push(new OpReverse(faces));
			emit finished();
		}
		return;
	}
}
